import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    user_name:'',
    nickname:'',
    user_photo:'',
    role:'',
    address:'',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    removeToken()
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INFO: (state, info) => {
    state.user_name = info.user_name
    state.nickname = info.nickname
    state.user_photo = info.user_photo
    state.role = info.role
    state.address = info.address
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ user_name: username.trim(), password: password }).then(response => {
        const { data } = response
          console.log(data.user.role)
        if(data.user.role=='admin'){
          commit('SET_TOKEN', data.token)
          commit('SET_INFO', data.user)
          setToken(data.token)
          resolve()
        }
        else reject()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  getInfo({ commit },userInfo) {
    commit('SET_INFO', userInfo)
  },

  // user logout
  logout({ commit, state }) {
    console.log('logout')
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

